﻿using SupportLayer.Constantes.Tabelas;
using SupportLayer.Constantes.Usuario;
using SupportLayer.Objetos.Usuario;
using SupportLayer.Util.ExtensionMethods;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;

namespace DataLayer
{
  public static class ConvertToObject
  {
    #region DataSet
    public static List<UsuarioClass> toUserClass(this DataSet ds)
    {
      List<UsuarioClass> lstUsuarios = new List<UsuarioClass>();

      if (ds.Tables.Count <= 0)
        return null;

      if (ds.Tables[0].Rows.Count <= 0)
        return null;



      foreach (DataRow dr in ds.Tables[0].Rows)
      {
        lstUsuarios.Add(new UsuarioClass()
        {
          ID = Convert.ToInt32(dr[USUARIO.ID].ToString()),
          Nome = dr[USUARIO.NOME].ToString(),
          Empresa = dr[USUARIO.EMPRESA].ToString(),
          Cargo = dr[USUARIO.CARGO].ToString(),
          Telefone = dr[USUARIO.TELEFONE].ToString(),
          Email = dr[USUARIO.EMAIL].ToString(),
          Login = dr[USUARIO.LOGIN].ToString(),
          Senha = dr[USUARIO.SENHA].ToString(),
          ComoConheceuTransys = dr[USUARIO.COMO_CONHECEU_TRANSYS].ToString(),
          VersaoAutoCad = dr[USUARIO.AUTOCAD_VERSAO].ToString(),
          ReceberInfoTransys = (dr[USUARIO.RECEBER_INFO_TRANSYS].ToString() == "1" ? true : false),
          DataCadastro = Convert.ToDateTime(dr[USUARIO.DATA_CADASTRO].ToString()),
          DataInativar = Convert.ToDateTime(dr[USUARIO.DATA_INATIVAR].ToString()),
          ConfirmouEmail = dr[USUARIO.CONFIRMOU_EMAIL].ToString()
        });
      }

      return lstUsuarios;
    }
    public static List<LogClass> toLogClass(this DataSet ds)
    {
      try
      {
        List<LogClass> lstLogs = new List<LogClass>();

        if ((ds.Tables.Count <= 0) || (ds.Tables[0].Rows.Count <= 0))
          return null;

        foreach (DataRow dr in ds.Tables[0].Rows)
        {
          lstLogs.Add(new LogClass()
          {
            Data = Convert.ToDateTime(dr[LOG.DATA]),
            ID = Convert.ToInt64(dr[LOG.ID].ToString()),
            QuantidadePlacas = Convert.ToInt32(dr[LOG.QUANTIDADE_PLACAS].ToString()),
            UsuarioID = Convert.ToInt32(dr[LOG.USUARIO_ID].ToString())
          });
        }

        return lstLogs;
      }
      catch (Exception)
      {
        throw;
      }
    }
    #endregion DataSet

    #region UsuarioClass
    public static string toSelectUserQueryString(this int ID)
    {
      return "select * from " + SupportLayer.Constantes.Tabelas.TABELAS.USUARIO +
              " where " + SupportLayer.Constantes.Usuario.USUARIO.ID + " = " + ID.ToString();
    }
    public static string toSelectUserQueryString(this string login, string senha)
    {
      return "select * from " + TABELAS.USUARIO +
              " where " + USUARIO.LOGIN + " = '" +
              login + "' and " + USUARIO.SENHA + " = '" + senha + "'";
    }
    public static string updateMailQueryString(this UsuarioClass usuario)
    {
      return "update " + TABELAS.USUARIO + " set " +
        USUARIO.CONFIRMOU_EMAIL + " = 'S'" +
        " where " + USUARIO.ID + " = " + usuario.ID;
    }
    public static string checkMailQueryString(this string mail)
    {
      return "select * from " + TABELAS.USUARIO + " where " + USUARIO.EMAIL + " = '" + mail + "'";
    }
    public static string checkUsernameQueryString(this string userName)
    {
      return "select * from " + TABELAS.USUARIO + " where " + USUARIO.LOGIN + " = '" + userName + "'";
    }
    #endregion UsuarioClass
    #region LogClass
    public static string toSelectLogQueryString(this DateTime _date, int UsuarioID)
    {
      try
      {
        return "select * from " + TABELAS.LOG +
          " where " + LOG.USUARIO_ID + " = " + UsuarioID +
          " and " + LOG.DATA + " = " + _date.toQueryDate();
      }
      catch (Exception)
      {
        throw;
      }
    }
    public static string toUpdateQueryString(this LogClass log)
    {
      return "update " + TABELAS.LOG + " set " +
        LOG.QUANTIDADE_PLACAS + " = " + log.QuantidadePlacas +
        " where " + LOG.USUARIO_ID + " = " + log.UsuarioID + " and " +
        LOG.DATA + " = " + log.Data.toQueryDate();
    }
    #endregion

    public static string toInsertQueryString(this object obj, string _nomeTabela)
    {
      Type type = obj.GetType();
      PropertyInfo[] properties = type.GetProperties();

      string separador = ", ";
      StringBuilder strB = new StringBuilder();
      strB.Append("insert into " + _nomeTabela + " (");

      List<string> nome_Campos = new List<string>();
      List<string> valores_Campos = new List<string>();

      for (int iProperty = 0; iProperty < properties.Count(); iProperty++)
      {
        PropertyInfo property = properties[iProperty];

        if (iProperty > 0)
        {
          if (property.GetValue(obj, null) == null)
            continue;

          string nome = ((DisplayAttribute)property.GetCustomAttributes(typeof(DisplayAttribute), true)[0]).Name;

          nome_Campos.Add(nome);

          var field_type = property.GetValue(obj, null);

          if (field_type.GetType().Equals(typeof(string)))
          {
            string campoString = "\"" + property.GetValue(obj, null).ToString() + "\"";
            valores_Campos.Add(campoString);
          }
          else if (field_type.GetType().Equals(typeof(DateTime)))
          {
            string campoData = Convert.ToDateTime(property.GetValue(obj, null)).toQueryDate();
            valores_Campos.Add(campoData);
          }
          else
            valores_Campos.Add(property.GetValue(obj, null).ToString());
        }
      }

      for (int iCampos = 0; iCampos < nome_Campos.Count; iCampos++)
        if (iCampos < nome_Campos.Count - 1)
          strB.Append(nome_Campos[iCampos] + separador);
        else
          strB.Append(nome_Campos[iCampos]);

      strB.Append(") values (");

      for (int iValores = 0; iValores < valores_Campos.Count; iValores++)
        if (iValores < valores_Campos.Count - 1)
          strB.Append(valores_Campos[iValores] + separador);
        else
          strB.Append(valores_Campos[iValores] + ")");

      return strB.ToString();
    }

  }
}